import * as Common from './common.js'
$.ajaxSettings.timeout = '3000';
var url = Common.UrlBase + Common.ApiEnums.UserMgr;
var loginBtn = document.getElementById("loginBtn");
loginBtn.onclick = function ()
{
    var account = document.getElementById("account").value;
    var pwd = document.getElementById("pwd").value;
    if (account.length >= 4 && pwd.length >= 5)
    {
        //login
        $.post(
            url,
            {
                "action": "loginUser",
                "account": account,
                "pwd": pwd
            },
            function (res)
            {
                console.log(res);
                const resobj = JSON.parse(res);
                console.log(resobj.data)

                if (resobj.code == "200")
                {

                    $.cookie('account', account, { expires: 7 });
                    $.cookie('user_id', resobj.data.user_id, { expires: 7 });
                    window.location.href = "server_list.html";
                } else if (resobj.code == "201")
                {
                    console.log(resobj.msg);
                    alert("账号不存在或密码错误");
                }

            }
        ).fail(function ()
        {
            alert("服务器维护中");
        });


    } else
    {
        alert("不可为空或者长度大于5")
    }

};
var registBtn = document.getElementById("registBtn");
registBtn.onclick = function ()
{
    var account = document.getElementById("account").value;
    var pwd = document.getElementById("pwd").value;
    if (account.length >= 4 && pwd.length >= 5)
    {
        $("#mymodal").modal("show");


    } else
    {
        alert("不可为空或者长度大于5")
    }
};
$(document).ready(function ()
{
    var registerCodeInput = $("#register_code");
    document.getElementById("mymodal").addEventListener('hide.bs.modal', event =>
    {
        if (registerCodeInput.val() == "buma")
        {
            //regist
            var account = document.getElementById("account").value;
            var pwd = document.getElementById("pwd").value;
            $.post(
                url,
                {
                    "action": "addUser",
                    "account": account,
                    "pwd": pwd
                },
                function (res)
                {
                    console.log(res)
                    if (res == "0")
                    {
                        console.log("register ok");
                        alert("注册成功，请点击登录");
                    } else if (res == "1")
                    {
                        console.log("exist");
                        alert("注册失败，此账号已存在");
                    } else
                    {
                        console.log("register error")
                        alert("注册错误");
                    }

                }
            ).fail(function ()
            {
                alert("服务器维护中");
            });
        } else
        {
            alert("注册码填写错误")
        }
    })
});